<template>
  <a-modal :title="currTitle" :width="450" :visible="visible" :closable="false" :maskClosable="closable">
    <template slot="footer">
      <a-button v-if="closable" @click="close">关闭</a-button>
      <a-button type="primary" @click="departOk">确认</a-button>
    </template>

    <a-form>
      <a-form-item
        :labelCol="{ span: 4 }"
        :wrapperCol="{ span: 20 }"
        style="margin-bottom: 10px"
        :validate-status="validate_status"
      >
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>您隶属于多结算组织，请选择当前所在结算组织</span>
          </template>
          <a-avatar style="background: #02a7f0" icon="gold" />
        </a-tooltip>
        <a-select
          v-model="accountSelected"
          :class="{ 'valid-error': validate_status == 'error' }"
          placeholder="请选择结算组织"
          style="margin-left: 10px; width: 80%"
        >
          <a-icon slot="suffixIcon" type="gold" />
          <a-select-option v-for="d in accountList" :key="d.id" :value="d.settlement_org_id">
            {{ d.settlement_org_name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { getAction, putAction } from '@/api/manage'
import Vue from 'vue'
import store from '@/store/'
import { USER_INFO } from '@/store/mutation-types'

export default {
  name: 'AccountSelect',
  props: {
    title: {
      type: String,
      default: '结算组织选择',
      required: false,
    },
    closable: {
      type: Boolean,
      default: false,
      required: false,
    },
    username: {
      type: String,
      default: '',
      required: false,
    },
  },
  watch: {
    username(val) {
      if (val) {
        this.loadDepartList()
      }
    },
  },
  data() {
    return {
      currTitle: this.title,
      visible: false,
      accountList: [],
      accountSelected: '',
      validate_status: '',
      currAccountName: '',
      currLoginUserName: '', //当前登录人userName
    }
  },
  created() {
    //this.loadDepartList()
    // this.queryCurrentAccountId()
    this.currLoginUserName = Vue.ls.get(USER_INFO).username
  },
  methods: {
    //查询当前结算组织id
    queryCurrentAccountId() {
      let apiUrl = '/finance/baseSettlementOrgUser/queryCurrentAccountId'
      let obj = {
        userName: this.currLoginUserName,
      }
      getAction(apiUrl, obj).then((res) => {
        this.accountSelected = res.message
      })
    },
    loadDepartList() {
      return new Promise((resolve) => {
        let url = '/sys/user/getCurrentUserAccountIds'
        this.currAccountName = ''
        getAction(url).then((res) => {
          if (res.success) {
            let accounts = res.result.list
            let accountId = res.result.accountId
            if (accounts && accounts.length > 0) {
              for (let i of accounts) {
                if (i.settlement_org_id == accountId) {
                  this.currAccountName = i.settlement_org_name
                  break
                }
              }
            }
            this.accountList = accounts
            if (this.currAccountName) {
              this.currTitle = '结算组织切换（当前结算组织 : ' + this.currAccountName + '）'
            }
          }
          resolve()
        })
      })
    },
    close() {
      this.accountClear()
    },
    departOk() {
      if (!this.accountSelected) {
        this.validate_status = 'error'
        return false
      }
      let obj = {
        accountId: this.accountSelected,
        username: this.username ? this.username : this.currLoginUserName,
      }
      putAction('/sys/selectAccountId', obj).then((res) => {
        if (res.success) {
          const userInfo = res.result.userInfo
          Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
          store.commit('SET_INFO', userInfo)
          //console.log("---切换组织机构---userInfo-------",store.getters.userInfo.orgCode);
          window.location.reload()
          this.accountClear()
        }
      })
    },
    show() {
      //如果组件传值username此处就不用loadDepartList了
      this.queryCurrentAccountId()

      this.loadDepartList().then(() => {
        this.visible = true
        if (!this.accountList || this.accountList.length <= 0) {
          this.$message.warning('您尚未设置结算组织信息!')
          this.accountClear()
        }
      })
    },
    accountClear() {
      this.accountList = []
      this.accountSelected = ''
      this.visible = false
      this.validate_status = ''
      this.currAccountName = ''
    },
  },
}
</script>
<style scoped>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>